package cn.restcloud.example.controller.apimgr;

import java.util.HashMap;

import cn.restcloud.framework.client.RestClient;
import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import cn.restcloud.framework.core.annotation.rest.RestRequestBody;
import cn.restcloud.framework.core.context.AppContext;
import cn.restcloud.framework.core.util.JsonUtil;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

/**
 * 调用系统提供的API实现在API网关中的注册一个API
 * @author Thinkpad
 *
 */
@BeanConfig(appId = "example",beanId = "ApiManagerRest",beanName = "API管理示例",beanType = BeanType.CONTROLLER,autowired = true,singleton = true,hotMode = true)
@RestConfig(url = "/rest/example/apimgr")
public class ApiManagerRest {
	@RestConfig(configName = "注册一个新的API",method = "POST",url = "/regnewapi")
	public DocAndView regNewApi()throws Exception{
		//注册API的系统Restful API
		AppContext.setDebug(true);
		String url="http://localhost:8080/restcloud/rest/core/services/save?abc=00009";
		
		//准备后端API的json信息
		HashMap<String,String> backendApiObj=new HashMap<String,String>();
		backendApiObj.put("method", "GET");
		backendApiObj.put("url", "http://192.168.1.1/api/test");
		backendApiObj.put("filterTransferHeader", "*");//要过滤的头
		backendApiObj.put("addTransferHeader", "{content-type:\"text/json\"}");//要追加的头,是一个json对像
		backendApiObj.put("timeout", "3000");//请求起时
		backendApiObj.put("requestBody", "1");//参数传送方式与请求保持一致
		
		//准备公开API的配置信息
		HashMap<String,String> apiobj=new HashMap<String,String>();
		apiobj.put("configType", "REG"); //标识为注册的API
		apiobj.put("appId", "gateway"); //要注册的应用appId，如果注册到网关中则是固定值gateway
		apiobj.put("configName", "测试注册API");
		apiobj.put("mapUrl", "/rest/api/test"); //注册后公开的API地址
		apiobj.put("beanId", "ServiceRegisterRest"); //注册restful API时的固定值
		apiobj.put("beanMethodName", "redirectUrl"); //注册restful API时的固定值
		apiobj.put("methodType", "GET");
		apiobj.put("requestBodyFlag", "false"); //是否requestbody请求
		apiobj.put("categoryId", "all"); //指定API注册所属分类
		apiobj.put("authType", "1"); //认证方式
		apiobj.put("regServiceUrl", JsonUtil.map2json(backendApiObj)); //注册的后端api的配置信息是一个json字符串
		String jsonStr=JsonUtil.map2json(apiobj);
		
		//请求url注册一个api接口
		String resultStr=RestClient.getInstance().setUrl(url).setRequestBodyStr(jsonStr).post().getResponseBody();
		
		return ViewUtil.getJsonView(resultStr);
	}
}
